package cn.gyn.gynrpc.core.cluster;

import cn.gyn.gynrpc.core.api.LoadBalancer;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡
 */
@Slf4j
public class RoundRibbonLoadBalancer<T> implements LoadBalancer<T> {
    //原子计数
    AtomicInteger index = new AtomicInteger();

    @Override
    public T choose(List<T> providers) {
        if (providers == null || providers.size() == 0) return null;
        if (providers.size() == 1) return providers.get(0);
        //用原子计数模服务数量
        int inc = index.incrementAndGet();
        log.info("index.incrementAndGet() % providers.size() ===> " + inc + "%" + providers.size() + "=" + inc % providers.size());
        return providers.get(inc % providers.size());
        //incrementAndGet会取到最大然后变成负数，可以&0x7fffffff,将符号位变为正数

        //return providers.get(index.incrementAndGet()&0x7fffffff % providers.size());
    }
}
